<?php
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Session;
class Login extends Controller {
	private $shangcheng_url;
	private $dsn_sc;
	private $username_sc;
	private $password_sc;
	
	public function _initialize(){
		parent::_initialize();
		$this->shangcheng_url = "http://sksc.quyum99.com";    //商城网站的网址
		$this->dsn_sc = 'mysql:dbname=lg566_com;host=127.0.0.1;port=3306';
		$this->username_sc = 'root';
		$this->password_sc = 'root';
	}
	//空操作
	public function _empty(){
		header("HTTP/1.0 404 Not Found");
		$this->display('Public:404');
	}
	public function aaa(){
		echo '1';
	}
    /**
     * 展示界面
     */
    public function index(){
    	
	    return $this->fetch();
    }
   	
    
    
    
    
    
    
    /**
     * 登录判断
     * @return Ambigous <\think\response\Json, \think\Response, \think\response\View, \think\response\Xml, \think\response\Redirect, \think\response\Jsonp, unknown, \think\Response>
     */
    public function check(){
    	if(IS_POST){
    		$nick = input('nick');
    		$pwd = md5(input('pwd'));
     		$r = Db::name('Users')->where(array('loginName'=>$nick))->find();
     		$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$r['userId']))->find();
    		if(!$r){
    			$data['status'] = -2;
    			$data['info'] = "用户名不存在";
    			return json($data);
    		}
    		if($member_relation['status'] == 2){
    			$data['status']=-3;
    			$data['info']="非常抱歉您的账号已被禁用";
    			return json($data);
    		}
    		if($member_relation['status'] == 0){
    			$data['status']=-3;
    			$data['info']="非常抱歉您的账号未激活";
    			return json($data);
    		}
    		//验证密码
    		if($r['loginPwd']!=$pwd){
    			$data['status']=-4;
    			$data['info']="密码输入错误";
    			return json($data);
    		}
       		session::set('USER_KEY_ID',$r['userId']);
       		session::set('USER_KEY',$r['loginName']);//用户名
       		$data['status'] = 1;
       		$data['info']="登录成功";
       		return json($data);
    	}else{
			$data['status']=-6;
       		$data['info']='请正确填写登录信息';
       		return json($data);
    	}
    }
   
    
    /**
     * 忘记密码
     */
    public function findpwd(){
        if(IS_AJAX){
           $phone = I('password');
		   $username = I('username');
		   $code = I('code');
		  
		  
		   $where['account'] = $username;
		   //$where['phone'] = $phone;
		   $res = M('Member')->where($where)->find();
		   if(empty($res)){
			   $data['status'] = -2;
			   $data['info'] = '未找到账号信息';
			   $this->ajaxReturn($data);
		   }
		   if($res['phone'] != $phone){
			   $data['status'] = -2;
			   $data['info'] = '账号绑定手机尾号为'.substr($res['phone'],-4,4);
			   $this->ajaxReturn($data);
		   }
		   $_SESSION['find_username'] = $username;
		   $_SESSION['find_phone'] = $phone;
		    //发送短信
		   //echo $phone;
		   $re = sandPhone($phone,'SK财富计划',C('sms_user'),C('sms_pass'));
		  // dump($re);die;
		   if($re['message'] == '短信发送成功'){
			   $data['status'] = 1;
			   $data['info'] = '短信发送成功';
			   $this->ajaxReturn($data);
		   }else{
			   $data['status'] = -3;
			   $data['info'] = $re['message'];
			   $this->ajaxReturn($data);
		   }
		   
		   
        }else{
            $this->display();
        }
    }
    /**
     * 重置密码
     */
    public function resetpwd(){
        if(IS_AJAX){
           $password = I('password','','md5');
		   $repwd = I('repwd','','md5');
		   $code = I('code');
		   //开始进行验证
		  if($_SESSION['code'] != $code || empty($code) || empty($_SESSION['find_username'])){
			   $data['status'] = -1;
			   $data['info'] = '短信验证码不正确';
			   $this->ajaxReturn($data);
		  }
		  if($password != $repwd || empty($password)){
			  $data['status'] = -1;
			   $data['info'] = '密码两次输入不一致';
			   $this->ajaxReturn($data);
		  }
		  $where['account'] = $_SESSION['find_username'];
		  $re = M('Member')->where($where)->setField('password',$password);
		  if($re){
			   $data['status'] = 1;
			   $data['info'] = '修改成功';
			   $this->ajaxReturn($data);
		  }else{
			   $data['status'] = -1;
			   $data['info'] = '修改失败';
			   $this->ajaxReturn($data);
		  }
		   
        }else{
            $this->display();
        }
    }
	
    /**
     * 退出
     */
    public function loginOut(){
        $_SESSION['USER_KEY_ID']=null;
        $_SESSION['USER_KEY']=null;
        $_SESSION['STATUS']=null;
        $this->redirect('Login/index');
    }
	
	
	public function reqs(){
		
		
		/*获取POST传值*/
		$user = $_POST['username'];
		$token = $_POST['token'];
		$password = md5(trim($_POST['password']));
		$zhuceid = $_POST['zhuceid']?$_POST['zhuceid']:0;
		
		/*设置商城数据库的配置参数*/
		$shangji = M('Member')->where("member_id={$zhuceid}")->find();
		if(!$shangji){
			$data['status'] = -1001;
			$data['info'] = '此上级ID不存在，请确认在进行申请';
		}
		
		//查看是否进行过申请
		$account = M('Member')->where("`account`='{$user}'")->find();
		if($account){
			$data['status'] = -2;
			$data['info'] = '您已经申请过，不能连续申请';
			$this->ajaxReturn($data);
		}
		/*****************************************从商城数据库中获取数据***********************************************/
		 try {
			$db = new \PDO($this->dsn_sc, $this->username_sc, $this->password_sc, array(\PDO::ATTR_PERSISTENT=>true));
		} catch(Exception $e) {
			die('Connect Failed Message: ' . $e->getMessage());
		}
		
		$sql="SELECT * FROM ecs_users WHERE user_name='{$user}';";
		
		$query = $db->query($sql);
			
		$query->setFetchMode(\PDO::FETCH_ASSOC);
		
		$table = $query->fetchAll();
			
		if(empty($table)){
			$data['status'] = -1;
			$data['info'] = '参数异常';
			$this->ajaxReturn($data);
		}
		
		if($token != md5(md5($table[0]['last_login']).$table[0]['email'])){
			$data['status'] = -1;
			$data['info'] = '参数异常';
			$this->ajaxReturn($data);
		}
		$arr['member_id'] = $table[0]['user_id'];
		$arr['account'] = $table[0]['user_name'];
		$arr['email'] = $table[0]['email'];
		$arr['phone'] = $table[0]['mobile_phone']?$table[0]['mobile_phone']:0;
		$arr['status'] = 0;
		$arr['sex'] = $table[0]['sex'];
		$arr['password'] = $password;
		$arr['zhuceid'] = $zhuceid;
		if($table[0]['birthday']){
			$birth = explode('-',$table[0]['birthday']);
		}else{
			$birth = array('0','0','0');
		}
		$arr['birthday_year'] = $birth[0];
		$arr['birthday_month'] = $birth[1];
		$arr['birthday_day'] = $birth[2];
		$arr['add_time'] = time();
		$re = M("Member")->add($arr);
		if(!re){
			$data['status'] = -1;
			$data['info'] = '参数异常';
			$this->ajaxReturn($data);
		}else{

			$ars['member_id'] = $table[0]['user_id'];
			$ars['tuijian_id'] = $zhuceid;
			$ars['add_time'] = time();
			$ars['status'] = 0;
			M('Shenqing')->add($ars);
			$data['status'] = 1;
			$data['info'] = '申请成功，等待审核';
			$data['user'] = $user;
			$data['token'] = $token;
			$this->ajaxReturn($data);
		}
		
	}
	/**
	*显示设置密码和推荐人
	*/
	public function req(){
		$user = $_POST['username'];
		$token = $_POST['token'];
		
		
		$this->assign('shangcheng_url',$this->shangcheng_url);
		$this->assign('username',$user);
		$this->assign('token',$token);
		$this->display();
	}
	/**
	*通知商城审核结果
	*/
	public  function reqend(){
		$member_id = I('post.member_id');
		$status = I('post.status');
		if(empty($member_id) || empty($status)){
			return false;
		}
		$member_info = M("Member")->where("member_id={$member_id}")->find();
		$account = $member_info['account'];
		$user_id = md5($member_info['member_id']);
		/***************************通知商城站审核结果**********************************/
			$url = $this->shangcheng_url."/user.php?act=reqend";
			
			$post_data = array ("u" => "$account","id"=>"$user_id","s" => "$status");
			//var_dump($post_data);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
			$output = curl_exec($ch);
			curl_close($ch);
			
			/*********************************************************************************/
	}
	/**
	*转账给商城
	*/
	public  function trans(){
		
		$member_id = I('post.member_id');
		//echo $member_id;die;
		$num = I('post.num');
		if(empty($member_id) || empty($num)){
			return false;
		}
		$member_info = M("Member")->where("member_id={$member_id}")->find();
		if($member_info['yibao'] < $num){
			
			return false;
		}
		$account = $member_info['account'];
		$rand = (int)(time()/100);
		$user_id = md5($member_info['member_id'].$rand);
		/***************************通知商城站审核结果**********************************/
			$url = $this->shangcheng_url."/user.php?act=trans_yibao";
			//echo $url;die;
			$post_data = array ("u" => "$account","id"=>"$user_id","n" => "$num");
			//var_dump($post_data);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
			$output = curl_exec($ch);
			curl_close($ch);
			echo $output;die;
			
			/*********************************************************************************/
	}
	
	/**
	 * 减购物积分方法（接口）
	 * @return boolean|unknown
	 */
	public function dec_money(){
		$user_id = I('post.user_id');
		$user_money = I('post.money');
		$strip = I('post.strip');
		if(empty($user_id)||empty($user_money)||empty($strip)){
			return false;
		}
		if($strip != md5($user_id.'aaaaa')){
			return false;
		}
		$money = abs($user_money);
		$res = M('Member')->where(array('member_id'=>$user_id))->setDec('xiaofei_num',$money);
		$this->addFinance($user_id,-$money,"购物消耗购物积分",47,2);
		return $res;
	}
	/**
	 * 添加财务日志方法
	 * @param unknown $member_id
	 * @param unknown $type
	 * @param unknown $content
	 * @param unknown $money
	 * @param unknown $money_type  收入=1/支出=2
	 * @param unknown $currency_id  币种id 0是rmb
	 * @return
	 */
	public function addFinance($member_id,$type,$content,$money,$currency_id){
		$data['member_id']=$member_id;
		$data['type']=$type;
		$data['content']=$content;
		$data['money']=$money;
		$data['add_time']=time();
		$data['currency_id']=$currency_id;
		$data['ip'] = get_client_ip();
		$list=M('K_finance')->add($data);
		if($list){
			return $list;
		}else{
			return false;
		}
	}
	
	/**
	 * 获取消费积分（接口）
	 * @return unknown
	 */
	public function get_money(){
		$user_id = I('post.user_id');
		//echo $user_id;
		$member = M('Member')->where(array('member_id'=>$user_id))->find();
		$xiaofei_money = $member['xiaofei_num'];
		echo  $xiaofei_money;
	}

	/**
	*测试接口
	*/
	public function strtofill(){
		$arr = '';
		foreach($_POST as $k=>$v){
			$arr .= $k . '=' . $v . '|';
		}
		file_put_contents('./1333.txt',$arr);
	}
	
}